package com.ruoyi.framework.mybaitsplus.handle;


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

@Slf4j
@Configuration
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 插入操作，自动填充
     *
     * @param metaObject m
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充[insert]...");
        // this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        // this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        fillBy("createBy", metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充[update]...");
        // this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        fillBy("updateBy", metaObject);
    }

    // 填充创建人
    private void fillBy(String value, MetaObject metaObject) {
        if (hasField(value, metaObject) && metaObject.getValue(value) == null) {
            try {
                String username = SecurityUtils.getUsername();
                if (StringUtils.isNotBlank(username)) {
                    this.setFieldValByName(value, username, metaObject);
                } else {
                    log.warn("创建人为空，无法填充 {} 字段！", value);
                }
            } catch (Exception e) {
                log.warn("获取用户名失败，填充 {} 字段失败：{}", value, e.getMessage());
                this.setFieldValByName(value, "miss", metaObject);
            }
        }
    }

    /**
     * 检查元对象是否包含指定字段
     *
     * @param metaObject 元对象
     * @return 是否存在该字段
     */
    private boolean hasField(String value, MetaObject metaObject) {
        return metaObject.hasGetter("createBy") || metaObject.hasSetter("createBy");
    }
}
